# -*- coding: utf-8 -*-

import webapp2
import exceptions

from classes import Person
from webapp2 import uri_for

STRING_LENGTH = 50

class ViewList(webapp2.RequestHandler):
    def get(self, *args, **kwargs):
        people_query = Person.query().order(Person.date_in)
        self.response.write("""<html><body>
        Здесь приведена таблица людей, находящихся в изоляторе медпункта, с возможностью их выписать:<br>
        <table border="1">
            <tr>
                <th>Фамилия</th>
                <th>Имя</th>
                <th>Дата помещения</th>
                <th>Комментарий</th>
                <th>Дата выписки</th>
                <th>Комментарий при выписке</th>
                <th>Выписка</th>
            </tr>""")
        for person_key in people_query.iter(keys_only=True):
            person = Person.get_by_id(person_key.id())
            if person.date_out != "":
                continue
            self.response.write("""
                <tr>
                    <td>%s</td>""" % (person.surname) )
            self.response.write("""
                    <td>%s</td>""" % (person.name) )
            self.response.write("""
                    <td>%s</td>""" % (person.date_in) )
            self.response.write("""
                    <td>%s</td>""" % (person.text) )
            self.response.write("""
                <form action="%s" method="post">
                    <td><input type="date" name="date%s"></td>
                    <td><textarea rows="5" cols="20" name="text%s"></textarea></td>
                    <td><input type="submit" value="Выписать">
                    <input type="hidden" name="id" value="%s"></td>
                </form>""" % (uri_for("delete"), person_key.id(), person_key.id(), person_key.id()))
        self.response.write("""</table><br>
            Добавить нового человека в список изолятора можно тут:
            <form action="%s" method="post"><input type="submit" value="Добавить"></form>
            Для просмотра истории нужно ввести начальную и конечную даты:<br>
            <form action="%s" method="post">
                <input type="date" name="date1">
                <input type="date" name="date2">
                <input type="submit" value="Показать историю">
            </from><br>\n
        <body><html>"""
        % (uri_for("add"), uri_for("history")) )


class AddPerson(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(AddPerson, self).__init__(*args, **kwargs)

    def post(self):
        self.response.write("<html><body>\n")
        self.response.write("""<table>
        <form action="%s" method="post"> <input type="hidden" name="new" value="yes">
            <tr>
                <td><label for="surname">Фамилия:</label></td>
                <td><input id="surname" type="text" name="surname"></td>
            </tr>

            <tr>
                <td><label for="name">Имя</label></td>
                <td><input id="name" type="text" name="name"</td>
            </tr>

            <tr>
                <td>Комментарий:</td>
                <td><textarea rows="10" cols="45" name="text"></textarea></td>
            </tr>

            <tr>
                <td>Дата записи</td>
                <td><input type="date" name="date"></td>
            </tr>
            </table><br>
            <input type="submit" value="OK"></body>
        </form>
        <form action="%s" method="post">
            <input type="submit" value="Отмена"><input type="hidden" name="cancel" value="yes">
        </form>
        </body></html>
        """ % (uri_for("input"), uri_for("input")) )

class DeletePerson(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(DeletePerson, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        person_key = self.request.get("id")
        date = self.request.get("date" + person_key)
        person = Person.get_by_id(int(person_key))
        person.date_out = date
        if person.date_out < person.date_in or person.date_out == "":
            self.redirect(uri_for("error"))
            return
        new_text = self.request.get("text" + person_key)
        for i in range(STRING_LENGTH, len(new_text), STRING_LENGTH):
            new_text = new_text[:i] + "<br>" + new_text[i:]
        person.text = person.text + u"<br><br>Комментарии при выписке:<br>" + new_text
        person.put()
        self.redirect(uri_for("show"))

class ShowHistory(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ShowHistory, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        people_query = Person.query().order(Person.date_in)
        time_begin = self.request.get("date1")
        time_end = self.request.get("date2")
        if time_end < time_begin:
            self.redirect(uri_for("error"))
        self.response.write("""
        <html><body>
        <table border="1">
            <tr>
                <th>Фамилия</th>
                <th>Имя</th>
                <th>Дата помещения</th>
                <th>Дата выписки</th>
                <th>Комментарии</th>
            </tr>""")
        for person in people_query:
            if time_begin == "" or time_end == "":
                break
            if (time_begin <= person.date_in and person.date_in <= time_end) or \
                    (time_begin <= person.date_out and person.date_out <= time_end) or \
                    (person.date_in <= time_begin and time_begin <= person.date_out)\
                    or (person.date_out == "" and person.date_in <= time_end):
                self.response.write("""
                <tr>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                </tr>
                """ % (person.surname, person.name, person.date_in, person.date_out, person.text))
        self.response.write("""
        </table><br>
        <form action="%s" method="post">
            <input type="submit" value="Вернуться"><input type="hidden" name="cancel" value="yes">
        </form>""" % uri_for("input"))
        self.response.write("</body></html>")


class InputPerson(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(InputPerson, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        if self.request.get("cancel") == "yes":
            self.redirect(uri_for("show"))
            return
        if self.request.get("new") == "yes":
            new_person = Person()
            new_person.surname = self.request.get("surname")
            new_person.name = self.request.get("name")
            new_person.date_in = self.request.get("date")
            new_text = self.request.get("text")
            for i in range(STRING_LENGTH, len(new_text), STRING_LENGTH):
                new_text = new_text[:i] + "<br>" + new_text[i:]
            new_person.text = new_person.text + new_text
            if new_person.name == "" or new_person.surname == "" or new_person.date_in == "":
                self.redirect(uri_for("error"))
                return
            new_person.put()
            self.redirect(uri_for("show"))

class Error(webapp2.RequestHandler):
    def get(self, *args, **kwargs):
        self.response.write("""
        <html><body>
            Ошибка! Вы неправильно ввели данные.
            <form action="%s" method="post">
                <input type="submit" value="Вернуться">
                <input type="hidden" name="cancel" value="yes">
            </form>
        </body></html>""" % (uri_for("input")))